package repository

import (
	"ruanGongKeShe16Zu/db"
	"ruanGongKeShe16Zu/model"
	"ruanGongKeShe16Zu/service/vo"

	"gorm.io/gorm"
)

type IOrderRepository interface {
	Create(order *model.Order) (*model.Order, error)
	SelectById(id int) (*model.Order, error)
	Update(order model.Order, newOrder vo.OrderReq) (*model.Order, error)
	DeleteById(id int) error
	OrderList(req *vo.ListOrderReq) ([]*model.Order, error)
	SelectByUserID(req *vo.ListOrderReq, id uint) ([]*model.Order, error)
}

type OrderRepository struct {
	DB *gorm.DB
}

func NewOrderRepository() IOrderRepository {
	return OrderRepository{DB: db.GetDB()}
}

func (o OrderRepository) Create(order *model.Order) (*model.Order, error) {
	if err := o.DB.Create(&order).Error; err != nil {
		return nil, err
	}
	return order, nil
}

func (o OrderRepository) SelectById(id int) (*model.Order, error) {
	var order model.Order
	if err := o.DB.First(&order, id).Error; err != nil {
		return nil, err
	}
	return &order, nil
}

func (o OrderRepository) Update(order model.Order, newOrder vo.OrderReq) (*model.Order, error) {
	if err := o.DB.Model(&order).Updates(newOrder).Error; err != nil {
		return nil, err
	}
	return &order, nil
}

func (o OrderRepository) DeleteById(id int) error {
	order, err := o.SelectById(id)
	if err != nil {
		return err
	}
	if err := o.DB.Delete(order).Error; err != nil {
		return err
	}
	return nil
}

func (o OrderRepository) OrderList(req *vo.ListOrderReq) ([]*model.Order, error) {
	if req.PageSize != 0 {
		var orders []*model.Order
		if err := o.DB.Order("created_at desc").Offset((req.PageNum - 1) * req.PageSize).Limit(req.PageSize).Find(&orders).Error; err != nil {
			return nil, err
		}
		return orders, nil
	}
	var orders []*model.Order
	if err := o.DB.Find(&orders).Error; err != nil {
		return nil, err
	}
	return orders, nil
}

func (o OrderRepository) SelectByUserID(req *vo.ListOrderReq, id uint) ([]*model.Order, error) {
	if req.PageSize != 0 {
		var orders []*model.Order
		if err := o.DB.Where("user_id = ?", id).Order("created_at").Offset((req.PageNum - 1) * req.PageSize).Limit(req.PageSize).Find(&orders).Error; err != nil {
			return nil, err
		}
		return orders, nil
	}
	var orders []*model.Order
	if err := o.DB.Where("user_id = ?", id).Find(&orders).Error; err != nil {
		return nil, err
	}
	return orders, nil
}
